package org.saratogaschools.edd.firefighter.client.activity;

import java.util.List;

import org.saratogaschools.edd.firefighter.client.ClientFactory;
import org.saratogaschools.edd.firefighter.client.place.FireListPlace;
import org.saratogaschools.edd.firefighter.client.place.FirePlace;
import org.saratogaschools.edd.firefighter.client.util.AsyncPlaceChange;
import org.saratogaschools.edd.firefighter.shared.model.Fire;
import org.saratogaschools.edd.firefighter.shared.model.FireFighter;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class CheckInActivity extends AbstractActivity implements CheckInView.Presenter {
	
	private FireFighter fighter;
	private Fire fire;
	private ClientFactory clientFactory;
	private CheckInView view;

	public CheckInActivity(FirePlace place, ClientFactory clientFactory) {
		this.fighter = place.getFighter();
		this.fire = place.getFire();
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		this.view = new CheckInView();
		view.setPresenter(this);
		panel.setWidget(view);
		List<String> peopleFighting = fire.getFighters();
		view.setCheckedIn(peopleFighting.contains(fighter.getName()));
	}

	@Override
	public void checkIn() {
		if (fire.getFighters().contains(fighter.getName()) == false) {
			fire.getFighters().add(fighter.getName());
		}
		persistFire();
	}

	@Override
	public void checkOut() {
		fire.getFighters().remove(fighter.getName());
		persistFire();
	}
	
	private void persistFire() {
		clientFactory.getService().updateFire(fire, new AsyncCallback<Void>() {
			public void onFailure(Throwable caught) {}
			public void onSuccess(Void result) {
				back();
			}
		});
	}
	
	@Override
	public void back() {
		GWT.runAsync(new AsyncPlaceChange(clientFactory, new FireListPlace(fighter)));
	}

}
